package reflectionAndDynamic;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.net.URL;
import java.net.URLClassLoader;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;

public class JavaCompilerTest {

	public static void main(String[] args) throws Exception {
		// Prepare source somehow.
		String source = "public class JavaCompilerTest { static { System.out.println(\"etc\"); } }";

		// Save source in .java file.
		File root = new File("f:\\LAB\\myetctests\\src\\reflectionAndDynamic\\");
		File sourceFile = new File(root, "GetNameOfCallingClass.java");
		System.out.println(sourceFile.getPath());
		System.out.println(sourceFile.getAbsolutePath());
		Writer writer = new FileWriter(sourceFile);
		writer.write(source);
		writer.close();

		// Compile source file.
		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
		compiler.run(null, null, null, sourceFile.getPath());

		// Load compiled class.
		URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { root.toURI().toURL() });
		Class<?> cls = Class.forName("JavaCompilerTest", true, classLoader); // Prints
																				// "test".
	}
}